package com.sharkburner.common.dao.paginator;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.vaadin.addons.lazyquerycontainer.Query;

/**
 * 
 * @author piu
 * 
 */
@Component
public class PaginationFactory {

    @Autowired
    private LazyQueryFactory lazyQueryFactory;

    @Autowired
    private LazyCriteriaFactory lazyCriteriaFactory;

    public LazyFactory getFactory(Object object) {
	LazyFactory factory = null;

	if (object instanceof Query) {
	    factory = lazyQueryFactory;
	} else if (object instanceof DetachedCriteria) {
	    factory = lazyCriteriaFactory;
	}
	factory.setDataProvider(object);

	return factory;
    }

    public static Object cloneDataProvider(Object dataProvider) {
	try {
	    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	    ObjectOutputStream outputStream = new ObjectOutputStream(
		    byteArrayOutputStream);
	    outputStream.writeObject(dataProvider);

	    ObjectInputStream inputStream = new ObjectInputStream(
		    new ByteArrayInputStream(
			    byteArrayOutputStream.toByteArray()));
	    return inputStream.readObject();

	} catch (IOException e) {
	    return null;
	} catch (ClassNotFoundException e) {
	    return null;
	}
    }
}
